package homework6.exp4;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

/**
 * @author fengq
 */
public class Dom4jReadExample {
    public void iterateWholeXML(String filename, HashMap<String ,String > hashMap){
        SAXReader saxReader=new SAXReader();
        try {
            //获取文档
            Document document = saxReader.read(new File(filename));
            //获取根元素
            Element root = document.getRootElement();
            int num=-1;
            for(Iterator iterator=root.elementIterator();iterator.hasNext();){
                Element element=(Element)iterator.next();
                num++;
                //获取标签的属性
                Attribute ageAttr = element.attribute("age");
                if (ageAttr!=null){
                    //获取属性的指
                    String age = ageAttr.getValue();
                    if (age!=null&&!age.equals("")){
                        hashMap.put(element.getName()+"-"+ageAttr.getName()+num,age);
                    }else {
                        hashMap.put(element.getName()+"-"+ageAttr.getName()+num,"20");
                    }
                }else {
                    hashMap.put(element.getName()+"-age"+num,"20");
                }

                for (Iterator iterInner=element.elementIterator();iterInner.hasNext();){
                    Element elementInner=(Element)iterInner.next();
                    if (elementInner.getName().equals("college")){
                        hashMap.put(elementInner.getName()+num,elementInner.getText());
                        Attribute leaderAttr = elementInner.attribute("leader");
                        if (leaderAttr!=null){
                            String leader=leaderAttr.getValue();

                            if (leader!=null&&leader.equals("")){
                                hashMap.put(elementInner.getName()+"-"+leaderAttr.getName()+num,leader);
                            }else {
                                hashMap.put(elementInner.getName()+"-"+leaderAttr.getName()+num,"leader");
                            }
                        }else {
                            hashMap.put(elementInner.getName()+"-leader"+num,"leader");
                        }
                    }else {
                        hashMap.put(elementInner.getName()+num,elementInner.getText());
                    }
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}
